<template>
  <div id="real-time-traffic" @click="showRoadState">实时路况</div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { Query } from "../../../utils/Query";
const $map = ref();
const source=ref()
const layer=ref()
const isShow = ref(false);

onMounted(() => {
  //获取地图
  $map.value = inject("$map");
  //设置空图层
  source.value = new ol.source.Vector({});
 layer.value = new ol.layer.Vector({
    source:source.value
  });
});

//点击显示关闭道路情况
function showRoadState() {
  const service = {
    name: "guanggu",
    layerId: 1,
  };

  // 是否显示
  isShow.value = !isShow.value;
  //判断是否显示
  if (isShow.value) {
    // 查询道路数据
    Query.queryByLayerId({
      service,
      callback: (res) => {
        // 获取数据,配置geojson数据
        let roadData = {
          type: "FeatureCollection",
          features: [],
        };
        res.SFEleArray.forEach((item) => {
          const coordinates = item.fGeom.LinGeom[0].Line.Arcs[0].Dots.map(
            (item) => [item.x, item.y]
          );
          roadData.features.push({
            type: "Feature",
            geometry: {
              type: "LineString",
              coordinates,
            },
            properties: {
              name: item.AttValue[3],
              id: item.AttValue[2],
              flow: item.AttValue[4],
              area: item.AttValue[5],
            },
          });
        });
        // 数据放入数据源中
        var features = new ol.format.GeoJSON().readFeatures(roadData);
        source.value.addFeatures(features);
        //根据不同的车流量生成不同颜色的线
        source.value.forEachFeature((item) => {
          let color = null;
          let flow = item.values_.flow;
          if (flow >= 1500) {
            color = "red";
          } else if (flow > 1000 && flow < 1500) {
            color = "yellow";
          } else if (flow <= 1000) {
            color = "green";
          }
          let stateStyle = new ol.style.Style({
            stroke: new ol.style.Stroke({
              width: 6,
              color,
            }),
          });
          item.setStyle(stateStyle);
        });
        $map.value.addLayer(layer.value);
      },
    });
  } else {
    $map.value.removeLayer(layer.value);
  }
}
</script>

<style lang="scss" scoped>
</style>
